package com.service.gmall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.gmall.common.constant.SysRedisConst;
import com.service.gmall.common.util.Jsons;
import com.service.gmall.common.util.MD5;
import com.service.gmall.model.user.UserInfo;
import com.service.gmall.model.vo.user.LoginSuccessVo;
import com.service.gmall.user.service.UserInfoService;
import com.service.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author alpha
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2022-09-07 01:43:28
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {
    @Autowired
    UserInfoMapper infoMapper;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginSuccessVo login(UserInfo info) {
        LoginSuccessVo successVo = new LoginSuccessVo();
        //查库
        UserInfo userInfo = infoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getLoginName, info.getLoginName())
                .eq(UserInfo::getPasswd, MD5.encrypt(info.getPasswd())));
        //登录成功
        if (!StringUtils.isEmpty(userInfo)){
            //设置令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            //存到redis
            redisTemplate.opsForValue().set(SysRedisConst.LOGIN_USER+token,
                    Jsons.toStr(userInfo),
                    7,
                    TimeUnit.DAYS);
            successVo.setNickName(info.getNickName());
            successVo.setToken(token);
            return successVo;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }
}




